<template>
  <div id="pmslist">
    <div class="tree-table">
      <el-tree :expand-on-click-node="false" ref="dataTree" :default-expand-all="true" :data="clsList" :props="defaultProps" node-key="id" highlight-current
        @node-click="handleClickClass" class="tools-tree">
        <template #default="{  data }">
          <div class="custom-tree-node">
            <span>{{ data.name }}</span>
            <span>
              <el-button v-if="data.id===null" type="success" class="addCirBtn" size="small" icon="Plus" circle @click="appendClass()"></el-button>
              <template v-else>
                <el-button type="warning" class="cirBtn" size="small" icon="EditPen" circle @click="editClass(data)"></el-button>
                <el-button type="info" class="cirBtn" size="small" icon="Delete" circle @click="deleteClass(data.id)"></el-button>
              </template>
            </span>
          </div>
        </template>
      </el-tree>
      <div class="tools">
        <el-divider content-position="left">{{sltClassNode.name}}</el-divider>
        <el-button class="addAdvBtn" type="primary" @click="handleAddPms">新建权限</el-button>
        <el-table v-loading="loading" row-key="id" :data="pmsList">
          <el-table-column label="序号" width="70" align="center">
            <template #default="scope">
              <span>{{scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="handleEditPms(scope.row)">{{scope.row.name}}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="编号" width="100" align="center"></el-table-column>
          <el-table-column label="类型" width="100" align="center">
            <template #default="scope">{{formatType(scope.row.type)}}</template>
          </el-table-column>
          <el-table-column label="操作范围" width="150" align="center">
            <template #default="scope">{{formatRange(scope.row.range)}}</template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button size="small" icon="EditPen" type="primary" plain circle @click="handleEditPms(scope.row)"></el-button>
              <el-button size="small" type="danger" icon="Delete" plain circle @click="handleDeletePms(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="权限分类设置" :show-close="false" v-model="showDialog" :close-on-click-modal="false" width="500px">
        <el-form ref="clsFormRef" :model="clsForm" :rules="clsRule" label-width="60px" class="form-input-m" :inline-message="true">
          <el-form-item prop="name" label="名称">
            <el-input type="text" v-model="clsForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="编号">
            <el-input type="text" v-model="clsForm.code" placeholder="请输入编号"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="saveClass(clsFormRef)">保存</el-button>
          <el-button @click="closeClsDialog(clsFormRef)">取消</el-button>
        </template>
      </el-dialog>
      <el-dialog title="权限点设置" :show-close="false" v-model="showPmsDialog" :close-on-click-modal="false" width="500px">
        <!-- 权限点表单 -->
        <el-form ref="pmsFormRef" :model="pmsForm" :rules="pmsRule" label-width="100px" class="form-input-m" :inline-message="true">
          <el-form-item prop="name" label="名称">
            <el-input type="text" v-model="pmsForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="编号">
            <el-input type="text" v-model="pmsForm.code" placeholder="请输入编号"></el-input>
          </el-form-item>
          <el-form-item prop="type" label="类型">
            <el-radio-group v-model="pmsForm.type" @change="(changed:any)=>handleChange(changed)">
              <el-radio :label="0">功能权限</el-radio>
              <el-radio :label="2">数据权限</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="range" label="数据权限范围" v-show="pmsForm.type===2">
            <el-select v-model="pmsForm.range" placeholder="请选择数据范围">
              <el-option :value="0" label="本人创建数据"></el-option>
              <el-option :value="2" label="部门创建数据"></el-option>
              <el-option :value="4" label="机构所有数据"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="savePmsForm(pmsFormRef)">保存</el-button>
          <el-button @click="closePmsDialog(pmsFormRef)">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { notifyType, notifyMessage } from '../../utils/common';
import type { ElTree, FormInstance } from 'element-plus';
let { proxy }: any = getCurrentInstance();
let dataTree: any = ref<InstanceType<typeof ElTree>>();
let loading = ref(false);
const pmsFormRef = ref<FormInstance>();
const clsFormRef = ref<FormInstance>();
let clsList: any = reactive([
  {
    id: null,
    name: '权限分类',
    children: []
  }
]);
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 当前选中的节点
let sltClassNode = reactive({
  id: '',
  name: ''
});
let showDialog = ref(false);
let clsForm = reactive({
  id: '',
  name: '',
  code: ''
});
let clsRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
};
let pmsList: any = reactive([]);
let showPmsDialog = ref(false);
let pmsForm = reactive({
  id: '',
  classId: '',
  name: '',
  code: '',
  type: null,
  range: null
});
// 表单验证
let pmsRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入编号',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择类型',
      trigger: 'change'
    }
  ]
};

findClassList();

function findClassList() {
  const url = '/api/sys/findPermissionClassList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        clsList[0].children.length = 0;
        clsList[0].children.push(...res.data.classList);
        if (clsList[0].children.length > 0) {
          sltClassNode.id = clsList[0].children[0].id;
          sltClassNode.name = clsList[0].children[0].name;
          setCurClassNode(clsList[0].children[0].id);
          findPermissionList();
        }
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 光标定位在指定分类上
function setCurClassNode(nodeId: any) {
  nextTick(() => {
    dataTree.value.setCurrentKey(nodeId);
  });
}
function findPermissionList() {
  loading.value = true;
  pmsList.length = 0;
  const url = '/api/sys/findPermissionListByClassId';
  // 将标题的id给列表获取数据用到的的typeId
  proxy.$http
    .get(url, { params: { classId: sltClassNode.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        pmsList.push(...res.data.pmsList);
      }
      loading.value = false;
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}
function formatType(value: any) {
  switch (value) {
    case 0:
      return '功能权限';
    case 2:
      return '数据权限';
    default:
      return '';
  }
}
function formatRange(value: any) {
  switch (value) {
    case 0:
      return '本人创建数据';
    case 2:
      return '部门创建数据';
    case 4:
      return '机构所有数据';
    default:
      return '';
  }
}
// 切换权限类型时
function handleChange(label: any) {
  if (label === 0) {
    pmsForm.range = null;
  }
}
// 点击分类项
function handleClickClass(obj: any) {
  if (obj.id === null) {
    return;
  }
  sltClassNode.id = obj.id;
  sltClassNode.name = obj.name;
  findPermissionList();
}
//添加分类
function appendClass() {
  showDialog.value = true;
}
// 编辑分类
function editClass(row: any) {
  clsForm.id = row.id;
  clsForm.name = row.name;
  clsForm.code = row.code;
  showDialog.value = true;
}
//保存
function saveClass(clsFormRef: any) {
  if (!clsFormRef) return;
  clsFormRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    //判断添加和编辑
    let url = '';
    if (clsForm.id) {
      url = '/api/sys/editPermissionClass';
    } else {
      url = '/api/sys/addPermissionClass';
    }
    proxy.$http
      .post(url, clsForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showDialog.value = false;
          if (clsForm.id) {
            // 编辑保存
            const curNode = dataTree.value.getCurrentNode();
            curNode.name = clsForm.name;
            curNode.code = clsForm.code;
            sltClassNode.id = clsForm.id;
            sltClassNode.name = clsForm.name;
          } else {
            // 添加保存
            const temp = {
              id: res.data.pmsClassId,
              name: clsForm.name,
              code: clsForm.code
            };
            clsList[0].children.push(temp);
            setCurClassNode(temp.id);
            sltClassNode.id = temp.id;
            sltClassNode.name = temp.name;
            findPermissionList();
          }
          clearClassForm();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}

function clearClassForm() {
  clsForm.id = '';
  clsForm.name = '';
  clsForm.code = '';
}
// 取消添加
function closeClsDialog(clsFormRef: any) {
  if (!clsFormRef) return;
  clsFormRef.clearValidate();
  clearClassForm();
  showDialog.value = false;
}
// 删除
function deleteClass(id: string) {
  proxy
    .$confirm('确定删除此分类?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deletePermissionClass';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findClassList();
            if (clsList[0].children.length > 0) {
              setCurClassNode(clsList[0].children[0].id);
            }
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
function handleAddPms() {
  if (!sltClassNode.id) {
    notifyMessage('请先添加分类', notifyType.warning, proxy);
    return;
  }
  showPmsDialog.value = true;
  pmsForm.classId = sltClassNode.id;
}
function handleEditPms(row: any) {
  pmsForm.id = row.id;
  pmsForm.classId = row.classId;
  pmsForm.name = row.name;
  pmsForm.code = row.code;
  pmsForm.type = row.type;
  pmsForm.range = row.range;
  showPmsDialog.value = true;
}
function savePmsForm(pmsFormRef: any) {
  if (!pmsFormRef) return;
  pmsFormRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const postData = {
      id: pmsForm.id,
      classId: pmsForm.classId,
      name: pmsForm.name,
      code: pmsForm.code,
      type: pmsForm.type,
      range: pmsForm.range
    };

    //判断添加和编辑
    let url = '';
    if (pmsForm.id) {
      url = '/api/sys/editPermission';
    } else {
      url = '/api/sys/addPermission';
    }
    proxy.$http
      .post(url, postData)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showPmsDialog.value = false;
          clearPmsForm();
          findPermissionList();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}
function clearPmsForm() {
  pmsForm.id = '';
  pmsForm.name = '';
  pmsForm.code = '';
  pmsForm.type = null;
  pmsForm.range = null;
  pmsForm.classId = '';
}
function closePmsDialog(pmsFormRef: any) {
  if (!pmsFormRef) return;
  pmsFormRef.clearValidate();
  clearPmsForm();
  showPmsDialog.value = false;
}
function handleDeletePms(id: string) {
  proxy
    .$confirm('确定删除此权限?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deletePermission';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findPermissionList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
</script>
<style lang="scss" scoped>
#pmslist {
  //左树右表结构
  .tree-table {
    // margin-top: 10px;
    display: flex;
    min-height: 400px;
    .tools-tree {
      width: 15%;
      min-width: 150px;
      margin: 0 0 0 0;
      padding: 5px;
      font-size: $font-size;
      border: none;
      .addCirBtn {
        width: 18px;
        height: 18px;
        padding: 0px;
        margin-left: 10px;
      }
      .cirBtn {
        display: none;
        width: 16px;
        height: 16px;
        padding: 0px;
        margin-left: 10px;
      }
      .el-tree-node__content:hover {
        .cirBtn {
          display: inline-block !important;
        }
      }
    }
    .tools {
      width: 85%;
      margin: 0 0 0 1px;
      .el-divider {
        width: 100%;
      }
      .el-divider--horizontal {
        margin: 7px 0 20px 0;
      }
      .addAdvBtn {
        margin-bottom: 10px;
      }
      .el-divider__text {
        font-size: $font-size;
      }
      .el-dialog__body {
        padding-top: 20px;
      }
      .divider {
        width: 310px;
        .el-divider__text {
          font-weight: bold;
          font-size: $font-size;
        }
      }
    }
  }
}
</style>